package com.hbhmzy.utils;


import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.util.AndroidException;
import android.util.Base64;
import android.util.Log;

import com.hbhmzy.call.SpeexUtil;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.security.KeyStore;
import java.util.Arrays;


public class LocalUDPDataReciever {
    private static LocalUDPDataReciever instance = null;
    private static final int SAMPLE_RATE = 8000; // 采样频率
    public static boolean listening=true;

    int speexLen = 1024;//一帧音频编码后的byte长度（20ms）与编码质量有关:Speex.open(int compression);
    int oneFrameSize = 1024;//窄带160,宽带320,超宽带640
    int  recbufSize;
    SpeexUtil speex = SpeexUtil.getInstance();


    public static LocalUDPDataReciever getInstance() {
        if (instance == null)
            instance = new LocalUDPDataReciever();
        return instance;
    }

    public void beforstart(){
        if(listening==false){
            startup();
        }else Log.e("startbefore", "已经开启监听了");
    }
    public void startup() {
        listening=true;
        new Thread(() -> {
            recbufSize = AudioTrack.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
            AudioTrack track = new AudioTrack(AudioManager.STREAM_VOICE_CALL, SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO,
                    AudioFormat.ENCODING_PCM_16BIT, recbufSize, AudioTrack.MODE_STREAM);
            oneFrameSize = speex.getFrameSize();
            track.play();
            try {
                //   Log.d(LocalUDPDataReciever.TAG, "本地UDP端口侦听中，端口=" + ConfigEntity.localUDPPort + "...");
                byte[] rbuf = new byte[38];
                //开始侦听
                while (listening) {
                    byte[] tem = new byte[ConfigEntity.packgeLength];
                    // 接收数据报的包
                    DatagramPacket packet = new DatagramPacket(tem, tem.length);
                    DatagramSocket localUDPSocket = LocalUDPSocketProvider.getInstance().getLocalUDPSocket();
                    if ((localUDPSocket == null) || (localUDPSocket.isClosed()))
                        continue;

                    // 阻塞直到收到数据
                    localUDPSocket.receive(packet);
                    // 解析服务端发过来的数据
                    //  String pFromServer = new String(packet.getData(), 0, packet.getLength(), "UTF-8");
                    Log.w("T", "收到消息:" + Arrays.toString(packet.getData()));

                    //不进行base64解密
//                    byte[] receviebyte = new byte[speexLen];
//                    System.arraycopy(packet.getData(), 0, receviebyte, 0, packet.getLength() );

                    byte[] base64 = Base64.decode(packet.getData(), Base64.DEFAULT);
                    byte[] receviebyte = new byte[speexLen];
                    System.arraycopy(base64, 0, receviebyte, 0, base64.length);

                    short[] linn = new short[oneFrameSize];
                    Log.e("tag", String.valueOf(base64.length));
                    speex.decode(receviebyte, linn, base64.length);
                    track.write(linn, 0, linn.length);
                }
                track.stop();
                track.flush();
                track.release();
            } catch (Exception eee) {
                Log.w("T", "本地UDP监听停止了(socket被关闭了?)," + eee.getMessage(), eee);
            }
        }).start();
    }

    public void endreciever(){
        listening=false;
    }


}